/**
 *
 *
 *
 *
 *
 */

package org.sxp.modules.oss.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.sxp.common.exception.XPException;
import org.sxp.common.utils.*;
import org.sxp.common.validator.ValidatorUtils;
import org.sxp.common.validator.group.LocalGroup;
import org.sxp.modules.oss.cloud.CloudStorageConfig;
import org.sxp.modules.oss.entity.SysOssEntity;
import org.sxp.modules.oss.service.SysOssService;
import org.sxp.modules.sys.entity.SysConfigEntity;
import org.sxp.modules.sys.service.SysConfigService;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 *
 *
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {
	@Autowired
	private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;

    @Value("${server.servlet.context-path}")
	private String contextPath;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:oss:all")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysOssService.queryPage(params);

		return R.ok().put("page", page);
	}


    /**
     * 云存储配置信息
     */
    @RequestMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }


	/**
	 * 保存云存储配置信息
	 */
	@RequestMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);

		if(config.getType() == Constant.CloudService.LOCAL.getValue()){
			//校验服务器本地数据
			ValidatorUtils.validateEntity(config, LocalGroup.class);
		}
		String configVal = sysConfigService.getValue(KEY);
        if(StringUtils.isNotBlank(configVal)){
			sysConfigService.updateValueByKey(KEY, JSON.toJSONString(config));
		}else{
			SysConfigEntity entity = new SysConfigEntity();
			entity.setParamKey(KEY);
			entity.setParamValue(JSON.toJSONString(config));
			entity.setRemark("云存储信息");
			sysConfigService.saveConfig(entity);
		}

		return R.ok();
	}
	

	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	@RequiresPermissions("sys:oss:all")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new XPException("上传文件不能为空");
		}

		//上传文件
//		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//		String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setId(UUID.randomUUID().toString().replace("-", ""));
		ossEntity.setUrl(contextPath + "sys/oss/download?keyId="+ ossEntity.getId());
		ossEntity.setData(file.getBytes());
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);

		return R.ok().put("url", ossEntity.getUrl());
	}

	/**
	 * 下载文件
	 */
	@GetMapping(value = "/download")
	@ApiOperation(value = "下载",produces = MediaType.IMAGE_JPEG_VALUE)
	@ResponseBody
	public void downloadNormal(
			@ApiParam(required = true, value = "文件ID", type = "path")
			@RequestParam String keyId,
			@ApiParam(required = false, value = "下载显示文件名")
			@RequestParam(required = false) String fileName,
			HttpServletResponse response) throws Exception {
		SysOssEntity ossEntity = sysOssService.getById(keyId);
		if(ossEntity != null){
			if(StringUtils.isBlank(fileName)){
				fileName = keyId;
			}

			response.setContentType(AeyeContentTypeUtil.contentType(fileName));
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			response.getOutputStream().write(ossEntity.getData());
		}
	}


	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody String[] ids){
		sysOssService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}

}
